<template>
  <div class="mi-canvas-tools-item" @click="handleDone">
    <Tooltip :content="$t('message.done')" :placement="G.mobile ? 'right' : 'top'">
      <span class="mi-canvas-tools-icon" style="cursor: pointer" :style="theme=='dark'?'color: #fff':''"> {{ $t('message.done') }} </span>
    </Tooltip>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import {Getter} from 'vuex-class';
import axios from 'axios'

@Component
export default class DragComponent extends Vue {
  @Prop() active: any;
  @Getter('getMathImg', {}) mathImg: any;
  @Getter('getTheme', {}) theme: any;
  @Getter('getCanvasBase64', {}) canvasBase64: any;

  getQueryParams(): { [key: string]: string | undefined } {
		const params: { [key: string]: string | undefined } = {};
		const queryString = window.location.search.substring(1);
		const vars = queryString.split("&");
		for (let i = 0; i < vars.length; i++) {
			const pair = vars[i].split("=");
			params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
		}
		return params;
	}

  base64ToFile(base64Data: string, filename: string): File {
		// 将base64的数据部分提取出来
		const parts = base64Data.split(';base64,');
		const contentType = parts[0].split(':')[1];
		const raw = window.atob(parts[1]);
		
		// 将原始数据转换为Uint8Array
		const rawLength = raw.length;
		const uInt8Array = new Uint8Array(rawLength);
		for (let i = 0; i < rawLength; ++i) {
		  uInt8Array[i] = raw.charCodeAt(i);
		}
		
		// 使用Blob对象创建文件
		const blob = new Blob([uInt8Array], {type: contentType});
		return new File([blob], filename, {type: contentType});
	}

  async handleDone() {
    // let params:any = {};
    // if(this.mathImg.imgUrl && this.mathImg.latexData){
    //   params = {
    //     big_img: this.mathImg.imgUrl,
    //     data: this.mathImg.latexData,
    //   };
    // }

    // const queryString = Object.keys(params)
    //   .map(
    //     (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    //   )
    //   .join("&");

    if(!this.canvasBase64) {
      window.parent.location.href = `${window.location.ancestorOrigins[0]}/snips`
      return
    }
    // @ts-ignore
    this.$Spin.show({
      render: (h) => {
          return h('div', [
              h('Icon', {
                  'class': 'demo-spin-icon-load',
                  props: {
                      type: 'ios-loading',
                      size: 24
                  }
              }),
              h('div', 'Loading')
          ])
      }
    })
    const time = Date.parse(new Date().toString())
    let fileName = `handWritten-${time}.png`
    let handWrittenId = null
    const user_id:string = this.getQueryParams().user_id as string;
    const theme:string = this.getQueryParams().theme as string;
    const session_id:string = this.getQueryParams().session_id as string;
    const req_data = {
      id: session_id,
      image: this.canvasBase64,
      done: true,
      theme,
      image_size: this.base64ToFile(this.canvasBase64, fileName).size,
    }
    await axios.post('https://web.ocrmath.com/v1/image/ocr_handwriting_image', req_data, {
			headers:{
				'Authorization': user_id,
				'Content-Type': 'application/json'
			}
		}).then(res => {
			if(res.data.errno == 0) {
				handWrittenId = res.data.data.image_id
			}else{
				this.$Message.error(res.data.msg)
			}
		}).catch(err => {
      this.$Message.error('错误')
		})
    // @ts-ignore
    this.$Spin.hide()
    let parentUrl = ''
    if (window.location.ancestorOrigins) {
      parentUrl = window.location.ancestorOrigins[0] + '/'
    } else {
      parentUrl = document.referrer
    }
    if(handWrittenId) {
      window.parent.location.href = `${parentUrl}snips/?handWrittenId=${handWrittenId}`
    }else{
      this.$Message.error('请重试')
    }
  }
}
</script>
<style>
.demo-spin-icon-load{
      animation: ani-demo-spin 1s linear infinite;
  }
</style>
